<template>
  <div class="header-search flexbox items-center">
    <slot name="left"></slot>
    <div class="search-input relative">
      <input v-if="isLocation" type="text" :placeholder="placeholder" @click.self="setSearchLocation">
      <input v-else type="text" v-model="keywords" @keyup="get(keywords,$event)" :placeholder="placeholder">
      <span class="search-icon header-sprites"></span>
    </div>
    <slot name="right"></slot>
    <ul v-if="searchResult.length!==0" class="search-result" model="out-in">
      <li v-for="item in searchResult" :key="item" @click="goSearch(item)">
        <i class="pull-right"></i>
        {{item}}
      </li>
    </ul>
  </div>
</template>
<script>
import mixin from "../../mixin";
import api from "../../http";
export default {
  mixins: [mixin],
  props: {
    isLocation: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      keywords: "",
      searchResult: [],
      flag: true,
      placeholder: "大家都在搜：手机"
    };
  },
  mounted() {
    if (!this.isLocation) {
      var ele = document.getElementsByClassName("search-input")[0].children[0];
      ele.focus();
    }
  },
  methods: {
    get(keys, evt) {
      this.searchResult = [];
      if (13 === evt.keyCode) {
        this.goSearch(keys);
        return false;
      }
      if (keys.length !== 0 && this.flag) {
        this.flag = false;
        api.get_search_list().then(response => {
          response.data.info.forEach(val => {
            this.searchResult.push(val);
            this.flag = true;
          });
        });
      }
    },
    goSearch(keys) {
      this.$router.push({ path: "/classify/result", query: { q: keys } });
    }
  }
};
</script>